import axios from "axios";
const request = axios.create({
    baseURL: '/api/',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    }
})


// localStorage.setItem('UserName', 'token')
// 请求拦截器
request.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('UserName')
        if (token) {
            config.headers['Authorization'] = token
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    (response) => {
        return response.data
    },
    (error) => {
        const status = error.response.status
        switch (status) {
            case 401:
                alert('token失效，请重新登录')
                break
            case 403:
                alert('权限不足')
                break
            case 404:
                alert('请求的资源不存在')
                break
            case 500:
                alert('服务器内部错误')
                break
            default:
                alert('请求失败，请稍后再试')
                break
        }
        return Promise.reject(error)
    }
)

export default request